package com.hn.kiss.config.conf;

import com.hn.kiss.config.common.CommonResult;
import com.hn.kiss.config.common.MyException;
import com.hn.kiss.config.common.ParmException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.mail.MailException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 统一异常处理
 * @author zxy
 */
@Slf4j
@ControllerAdvice
public class ExceptionConfig {

    /**
     * 统一异常处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handle(Exception ex) {
        String errorInfo = "";
        if (ex instanceof ConstraintViolationException) {//controller参数校验异常
            ConstraintViolationException exs = (ConstraintViolationException) ex;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                PathImpl path = (PathImpl)item.getPropertyPath();
                errorInfo += path.getLeafNode() + item.getMessage();
            }
            return CommonResult.validateFailed(errorInfo);
        }else if (ex instanceof MyException) {//自定义异常
            log.warn(ex.getMessage());
            return  CommonResult.failed(ex.getMessage());
        }else if (ex instanceof ParmException) {//自定义参数异常
            log.warn(ex.getMessage());
            return CommonResult.validateFailed(ex.getMessage());
        }else if(ex instanceof UsernameNotFoundException){//账号不存在
            log.warn(ex.getMessage());
            return CommonResult.validateFailed(ex.getMessage());
        }else if(ex instanceof MailException){
            log.warn(ex.getMessage());
            return CommonResult.failed("邮件发送异常,检查邮箱是否正确!");
        }else if(ex instanceof MethodArgumentTypeMismatchException){
            MethodArgumentTypeMismatchException me = (MethodArgumentTypeMismatchException)ex;
            String message = String.format("controller参数转换异常,%s : %s 转换 为 %s 异常", me.getName(), me.getValue(), me.getRequiredType().getName());
            log.warn(message);
            return CommonResult.validateFailed(message);
        }else{//系统异常
            ex.printStackTrace();
            for(StackTraceElement s : ex.getStackTrace()) {
                log.error(s.toString());
            }
            return CommonResult.error(ex.getMessage());
        }

    }
}
